<template>
  <div class="paprefile flex-center">
    <div class="download-btn flex-center pointer" @click="savePaperFile">
      <img class="icon-test" src="../../assets/img/test-download.png" alt="" />
      <div class="s-16 icon-de  pointer">下载</div>
    </div>
    <div class="conainer">
      <div v-for="page in pageCount" :key="page" class="page" style="position: relative">
        <canvas :id="'canvas-pdf' + page"></canvas>
        <div class="page-tips s-14 flex-center">第{{ page }}页/共{{ pageCount }}页</div>
      </div>
    </div>
  </div>
</template>

<script>
import mixin from '../../mixin/mixin'
import PDFJS from '../../../../../static/utils/pdf/pdf'
import { remote } from 'electron'
PDFJS.GlobalWorkerOptions.workerSrc = process.env.NODE_ENV === 'production' ? '../../../../app.asar/dist/electron/static/utils/pdf/pdf.worker.js' : '../../../../static/utils/pdf/pdf.worker.js'
export default {
  name: 'PaperFile',
  mixins: [mixin],
  data() {
    return {
      pdfScale: 2,
      pdfSrc: '',
      pageCount: 0 // pdf文件总页数
    }
  },
  mounted() {
    const path = require('path')
    const pdfSrc = path.join(window.$DATADIR, `resc/PaperFile/${this.bsr.id}.pdf`)
    this._pdfSrc = pdfSrc
    this.loadPDF(pdfSrc)
  },
  methods: {
    savePaperFile() {
      remote.dialog.showSaveDialog(
        {
          title: '选择下载位置',
          buttonLabel: '下载',
          defaultPath: this.bsr.name,
          filters: [
            {
              name: 'PDF',
              extensions: ['pdf']
            }
          ]
        },
        val => {
          if (!val) return
          const fs = require('fs')
          try {
            fs.copyFileSync(this._pdfSrc, val)
            this.$message.success('下载成功')
          } catch (error) {
            this.$message.error('下载失败')
          }
        }
      )
    },
    renderPDF(pdf, i, id) {
      pdf.getPage(i).then(page => {
        let canvas = document.getElementById(id)
        let ctx = canvas.getContext('2d')
        let dpr = window.devicePixelRatio || 1
        let bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1
        let ratio = dpr / bsr
        let viewport = page.getViewport({ scale: this.pdfScale })
        canvas.width = viewport.width * ratio
        canvas.height = viewport.height * ratio
        canvas.style.width = 59.028 + 'vw'
        // that.pdf_div_width = viewport.width + 'px'

        // canvas.style.height = '100%'

        ctx.setTransform(ratio, 0, 0, ratio, 0, 0)

        // 将 PDF 页面渲染到 canvas 上下文中
        let renderContext = {
          canvasContext: ctx,
          viewport: viewport
        }
        page.render(renderContext)
      })
    },
    //读取pdf文件，并加载到页面中
    loadPDF(fileURL) {
      // let mask = this.$downloadmask("#coursewareContainer", {
      //     title: '资源加载中',
      //     time: 15000,
      //     progress: false,
      // });
      let pdf = PDFJS.getDocument({ url: fileURL, rangeChunkSize: 65536 * 5 })
      pdf.promise.then(val => {
        // mask.close()
        this.pageCount = val.numPages
        val.getData().then(res => (this.pdfSize = res.byteLength))
        for (let i = 1; i <= val.numPages; i++) {
          let id = 'canvas-pdf' + i
          try {
            this.renderPDF(val, i, id)
          } catch (error) {
            console.log(error)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.paprefile {
  width: 100vw;
  height: calc(100vh - 30px);
  overflow-x: hidden;
  overflow-y: scroll;
  background: #fff;
  position: relative;
  .conainer {
    height: 100%;
  }
  .page-tips {
    position: absolute;
    bottom: 0;
    background-color: #fff;
    color: #000;
    width: 100%;
  }
  .page:not(:first-child) {
    margin-top: 10px;
  }
  .download-btn {
    position: absolute;
    right: 100px;
    top: 100px;
    .icon-test {
      width: 24px;
      height: 24px;
      margin-right: 7px;
      vertical-align: middle;
    }
  }
}
</style>
